package cn.edu.xmu.orderpayment.order.mq;

import cn.edu.xmu.oomall.core.util.JacksonUtil;
import cn.edu.xmu.orderpayment.order.constants.Constants;
import cn.edu.xmu.orderpayment.order.model.bo.Order;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author Yujie Lin
 * @date 2021/12/9 21:48
 */
@Service
public class RocketMQService {
    private static final Logger logger = LoggerFactory.getLogger(RocketMQService.class);

    @Resource
    private RocketMQTemplate rocketMQTemplate;


    // 生产者生产订单消息
    public void sendOrderMessage(Order order){

        String orderJson= JacksonUtil.toJson(order);
        logger.info("sendOrderMessage: send message orderId = "+order+" time =" + LocalDateTime.now());
        rocketMQTemplate.asyncSend("order-topic2", MessageBuilder.withPayload(orderJson).build(), new SendCallback() {

            @Override
            public void onSuccess(SendResult sendResult) {
                logger.info("已将order"+orderJson+"发送");
                logger.info("sendOrderMessage: onSuccess result = "+ sendResult+" time ="+LocalDateTime.now());
            }

            @Override
            public void onException(Throwable throwable) {
                logger.info("sendOrderMessage: onException e = "+ throwable.getMessage()+" time ="+LocalDateTime.now());
            }
        }, Constants.OUT_TIME * 1000);
    }


    // 生产者生产订单检查消息，30 minute 后发送，检查订单是否支付，未支付则取消
    public void sendOrderCheckMessage(String orderSn){

        logger.info("sendOrderMessage: send message orderId = "+orderSn+" delay ="+Constants.THIRTY_SECONDS_LEVEL+" time =" + LocalDateTime.now());
        rocketMQTemplate.asyncSend("order-check-topic2", MessageBuilder.withPayload(orderSn).build(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                logger.info("sendOrderCheckMessage: onSuccess result = "+ sendResult+" time ="+LocalDateTime.now());
            }

            @Override
            public void onException(Throwable throwable) {
                logger.info("sendOrderCheckMessage: onException e = "+ throwable.getMessage()+" time ="+LocalDateTime.now());
            }
        },Constants.OUT_TIME*1000,Constants.THIRTY_MINUTES_LEVEL);
    }


}
